package ua.kiev.tosik.price.conf;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class DbConfig {

	public static final String DB_CONFIG = "conf/db.properties";
	private static Logger logger = Logger.getLogger(DbConfig.class);
	private static DbConfig ourInstance;
	private File configFile;
	private EncryptedProperties ep;

	public static DbConfig getInstance() {
		if (ourInstance == null) {
			ourInstance = new DbConfig();
		}
		return ourInstance;
	}

	private DbConfig() {
		logger.debug("Initialize Encrypted DbConfig");
		configFile = new File(DB_CONFIG);
		if ( configFile.exists() ) {
			try {
				ep = new EncryptedProperties("q1w2e3r4");
				loadFile(ep);
			} catch (Exception e) {
				logger.error(e);
			}
		} else {
			logger.error("Db config file does not exist!");
		}
	}

	private void loadFile(EncryptedProperties ep) throws Exception {
		FileInputStream in = new FileInputStream(configFile);
		ep.load(in);
	}

	public String get(String key) {
		return ep.getProperty(key);
	}

	public synchronized void set(String key, String value) {
		ep.setProperty(key, value);
		try {
			logger.debug(this.getClass().getSimpleName() + ": save " + key + " = " + value);
			ep.store(new FileOutputStream(configFile), "Added by application");
		} catch (Exception e) {
			logger.error(e);
		}
	}

	public EncryptedProperties getEp() {
		return ep;
	}

}
